package com.bbx.taxi.client.UpdateChecker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.bbx.api.R;
import com.bbx.api.sdk.Config;
import com.bbx.api.sdk.SDK;
import com.bbx.api.sdk.model.passanger.VersionBuild;
import com.bbx.api.sdk.model.passanger.Return.Version;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.official.passanger.Official_VersionNet;
import com.bbx.api.sdk.net.passeger.conn.VersionNet;
import com.bbx.api.util.LogUtils;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.taxi.client.UpdateChecker.ui.MyProgressBar;
import com.bbx.taxi.client.UpdateChecker.ui.MyUpdateDailog;
import com.bbx.taxi.client.Util.VersionInfo;

import android.app.Activity;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class UpdateCheck  {
	private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor
			(5, 10, 3, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(10));
	private static final int MSG_LOAD=1;
	private static final int MSG_LOADFINISH=2;
	private static final int MSG_NO_SD=3;
	private static final int DOWNLOAD_FALURE = -1;
	private File apkFile;
	private String apkUrl;
	private String pathSavedDir;
	private String apkName ;
	// 下载进度条
	private MyProgressBar progressBar;
	//进度条显示数值
	private int progress = 0;
	private boolean isInterceptDownload=false;
	public interface OnUpdateListener{
		/**
		 * 更新成功，
		 */
		public void onUpdateSuccess(Version version);
		/**
		 * 更新失败,msg==null则不更新，msg!=null则请求失败
		 */
		public void onUpdateFailed(int status,String msg);
	}
	public OnUpdateListener mOnUpdateListener=null;
	/**
	 * 检查版本更新,且监听
	 */
	public void setOnUpdateListener(OnUpdateListener l,int platform,String channel){
		mOnUpdateListener=l;
		getLatestVersion(platform,channel);
		}
	/**
	 * 移除监听
	 */
	public void removeOnUpdateListener(){
		mOnUpdateListener=null;
		if (mVersionTask != null
				&& mVersionTask.getStatus() != AsyncTask.Status.FINISHED)
			mVersionTask.cancel(true);
	}
	private static UpdateCheck mCheckUpdate;
	public static Activity context;
	private VersionTask mVersionTask;
	
    public static UpdateCheck getInstance(Activity mContext){
    	context=mContext;
    	if(mCheckUpdate==null){      
    		mCheckUpdate=new UpdateCheck();
			return mCheckUpdate; 
			
		}
		else return mCheckUpdate;
    }
	/**
	 * 获取最新版本
	 */
	private void getLatestVersion(int platform,String channel){
		VersionBuild mVersionBuild=new VersionBuild(context);
		mVersionBuild.platform=platform;
		mVersionBuild.channel=channel;
		mVersionBuild.version=VersionInfo.getVersion(context);
		mVersionTask=new VersionTask(context, mVersionBuild);
		mVersionTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		
	}
	/**
	 * 版本
	 *
	 */
	public class VersionTask extends BaseAsyncTask {
		private VersionBuild mVersionBuild;
		public VersionTask(Context context, VersionBuild mVersionBuild) {
			super(context, false,0);
			this.mVersionBuild = mVersionBuild;
		}

		@Override
		protected Object doInBackground(Object... params) {
			return new Official_VersionNet(context,mVersionBuild.toJsonStr());
		}

		@Override
		public void onSuccess(Object object) {
			LogUtils.e("xxx", "---获取成功");
			if(object!=null){
				Version mVersion=(Version)object;
				if(mVersion.isUpdata()){
					//版本不同，执行更新
					if(mOnUpdateListener!=null)mOnUpdateListener.onUpdateSuccess(mVersion);
				}
				else{
					//版本相同
					if(mOnUpdateListener!=null)mOnUpdateListener.onUpdateFailed(0,null);
				}
			}
			else{
				if(mOnUpdateListener!=null)mOnUpdateListener.onUpdateFailed(0,null);
			}
		}

		@Override
		public void onFailed(int status, String msg) {
            if(mOnUpdateListener!=null)mOnUpdateListener.onUpdateFailed(status,msg);
		}
	}
		public void downloadApk(final String apkUrl, final String pathSavedDir) {
			this.apkUrl=apkUrl;
			this.pathSavedDir=pathSavedDir;
			final MyUpdateDailog dialog=new MyUpdateDailog(context);
			dialog.show();
			progressBar=dialog.getProgressBar();
			//开启另一线程下载
			MyThread mMyThread=new MyThread();
			mMyThread.setUri(apkUrl,pathSavedDir);
			mMyThread.start();
		} 
		
		/**
		 * 从服务器下载新版apk的线程
		 */
		private class MyThread extends Thread{
			String apkUrl;
			String pathSavedDir;
			public void setUri(String apkUrl,String pathSavedDir){
				this.apkUrl=apkUrl;
				this.pathSavedDir=pathSavedDir;
			}
			@Override
			public void run() {
				if (!android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
					//如果没有SD卡
				    handler.sendEmptyMessage(MSG_NO_SD);
				}else{
					try {
						//服务器上新版apk地址
						URL url = new URL(apkUrl);
						HttpURLConnection conn = (HttpURLConnection)url.openConnection();
						conn.connect();
						int length = conn.getContentLength();//获取文件大小
						InputStream is = conn.getInputStream();
						File file = new File(pathSavedDir);
						if(!file.exists()){
							//如果文件夹不存在,则创建
							file.mkdir();
						}
						
						//下载服务器中新版本软件（写文件）
						apkName = apkUrl.substring(apkUrl.lastIndexOf("/") + 1);
						String prefix=apkName.substring(apkName.lastIndexOf(".")+1);
						if(!prefix.equals(".apk")){
							apkName=apkName+".apk";
						}
						String apkFile = pathSavedDir+apkName;
						File ApkFile = new File(apkFile);
						FileOutputStream fos = new FileOutputStream(ApkFile);
						int count = 0;
						byte buf[] = new byte[1024];
						do{
							int numRead = is.read(buf);
							count += numRead;
							//更新进度条
							progress = (int) (((float) count / length) * 100);
							handler.sendEmptyMessage(MSG_LOAD);
							if(numRead <= 0){
								//下载完成通知安装
								Message msg=new Message();
								msg.what=MSG_LOADFINISH;
								msg.arg1=1;
								handler.sendMessage(msg);
								break;
							}
							fos.write(buf,0,numRead);
							//当点击取消时，则停止下载
						}while(!isInterceptDownload);
					} catch (MalformedURLException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		};
		/**
		 * 声明一个handler来跟进进度条
		 */
		private Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MSG_LOAD:
					// 更新进度情况
					progressBar.setProgress(progress);
					break;
				case MSG_LOADFINISH:
					progressBar.setVisibility(View.INVISIBLE);
					// 安装apk文件
					installApk(msg.arg1);
				case MSG_NO_SD://调用没有SD卡对话框
//					showSDcard();
					break;
				}
			};
		};
		
		/**
		 * 安装apk
		 */
		private void installApk(int panduan) {
			File apkfile = null;
			if(panduan==1){//等于1的时候代表为有安装在SD卡上
				// 获取当前sdcard存储路径
				apkfile  = new File(pathSavedDir+apkName);		
			}
			else if(panduan==2){//等于2的时候代表为有安装在手机内存上
				// 获取当前sdcard存储路径
				 apkfile = new File(context.getFilesDir()+"/"+apkName);
			}
			
			if (!apkfile.exists()) {
				return;
			}
			Intent i = new Intent(Intent.ACTION_VIEW);
		// 安装，如果签名不一致，可能出现程序未安装提示
			i.setDataAndType(Uri.fromFile(new File(apkfile.getAbsolutePath())), "application/vnd.android.package-archive"); 
			context.startActivity(i);
			context.finish();
		}
}
